package softtech.apps.callblocker;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import softtech.apps.utility.ApplicationConstants;
import softtech.apps.utility.ControlPhoneAction;
import softtech.apps.callblocker.adapter.AdapterChatSms;
import softtech.apps.callblocker.model.DatabaseHanler;
import softtech.apps.callblocker.model.SmsBlockedItem;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

public class ActivityChat extends Activity {

	Context mContext;

	final String TAG = "Activity Chat";

	private String mPhoneNumber;

	// Database
	DatabaseHanler db;
	int limitItemLoader;
	//
	// Page chat
	//
	ArrayList<SmsBlockedItem> listSms;

	AdapterChatSms adapterChatSms;

	ListView lvListChat;

	ImageView imgSmsSubmit;

	EditText edtSmsContentSubmit;

	android.support.v4.widget.SwipeRefreshLayout swipeContainer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.page_chat);
		mContext = this;
		db = new DatabaseHanler(this);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		initPhoneNumber();
		setIdPageChat();
		initListChat();
		initPageChat();
		setFunctionForPageChat();
		startServicePageChat(mContext);
	}

	/**
	 * Set id for any view in page chat
	 */
	void setIdPageChat() {
		edtSmsContentSubmit = (EditText) findViewById(R.id.edtSmsContentSubmit);
		imgSmsSubmit = (ImageView) findViewById(R.id.imgSmsSubmit);
		lvListChat = (ListView) findViewById(R.id.lvListChat);
		swipeContainer = (android.support.v4.widget.SwipeRefreshLayout) findViewById(R.id.swipe_container);
	}

	/**
	 * Init phone number of this page
	 */
	void initPhoneNumber() {
		// de demo thoi :D
		mPhoneNumber = "1234";
		Intent intent = getIntent();
		mPhoneNumber = intent.getStringExtra("phonenumber");

	}

	/**
	 * init list chat
	 */
	void initListChat() {

		// for(int i = 0 ; i < 100 ; i++){
		// db.insertSmsBlockItem(new SmsBlockedItem(mPhoneNumber, "11-11-11",
		// SmsBlockedItem.RECEIVE, ""+i));
		// }
		limitItemLoader = 15;
		if(mPhoneNumber.contains("+")){
			listSms = db.getSmsBlockItem(null, SmsBlockedItem.PHONE_NUMBER + " LIKE ?",
					new String[] { "%" + mPhoneNumber.substring(4) +"%" }, SmsBlockedItem.DATE_TIME
					+ " DESC", "" + limitItemLoader);
		}else{
			listSms = db.getSmsBlockItem(null, SmsBlockedItem.PHONE_NUMBER + " LIKE ?",
					new String[] { "%" + mPhoneNumber.substring(2) +"%" }, SmsBlockedItem.DATE_TIME
					+ " DESC", "" + limitItemLoader);
		}
		
		reverseArrayList();
	}

	/**
	 * init page chat
	 */
	void initPageChat() {

		adapterChatSms = new AdapterChatSms(mContext,
				R.layout.item_search_notfound, listSms);
		lvListChat.setAdapter(adapterChatSms);
		lvListChat.setSelection(adapterChatSms.getCount() - 1);

	}

	/**
	 * set function for page chat
	 */
	void setFunctionForPageChat() {

		lvListChat.setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if (taskUpdateListView != null
						&& !taskUpdateListView.equals(null)
						&& !taskUpdateListView.stopped) {
					return;
				}
				int topRowVerticalPosition = (lvListChat == null || lvListChat
						.getChildCount() == 0) ? 0 : lvListChat.getChildAt(0)
						.getTop();

				swipeContainer.setEnabled(topRowVerticalPosition >= 0);
			}
		});

		swipeContainer.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				if (taskUpdateListView == null) {
					taskUpdateListView = new UpdateListView(mContext);
				} else {
					try {
						if (taskUpdateListView.stopped) {
							taskUpdateListView.cancel(true);
							taskUpdateListView = new UpdateListView(mContext);
						} else {
							return;
						}

					} catch (Exception e) {

					}
				}

				taskUpdateListView.execute(null, null, null);
			}
		});

		imgSmsSubmit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (edtSmsContentSubmit.getText().toString().trim().length() == 0) {
					return;
				}

				ControlPhoneAction.sendSMS(mPhoneNumber, edtSmsContentSubmit
						.getText().toString().trim());

				String last_out_date = "";
				Calendar cal = Calendar.getInstance();
				SimpleDateFormat sdf = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm");
				last_out_date = sdf.format(cal.getTime());

				SmsBlockedItem item = new SmsBlockedItem(mPhoneNumber,
						last_out_date, SmsBlockedItem.SEND, edtSmsContentSubmit
								.getText().toString().trim());
				if (listSms == null || listSms.equals(null)
						|| listSms.size() == 0) {
					listSms = new ArrayList<SmsBlockedItem>();
					listSms.add(item);
					adapterChatSms = new AdapterChatSms(mContext,
							R.layout.item_search_notfound, listSms);
					lvListChat.setAdapter(adapterChatSms);
					edtSmsContentSubmit.setText("");
					return;
				}
				listSms.add(item);
				adapterChatSms.notifyDataSetChanged();
				lvListChat.setSelection(adapterChatSms.getCount());
				edtSmsContentSubmit.setText("");
				db.insertSmsBlockItem(item);

			}
		});

	}

	@Override
	public void onBackPressed() {
		
		// getinten ; if =0 return activitycallhistory else return infomation
		Intent inDash = new Intent(ActivityChat.this,
				ActivityCallHistory.class);
		startActivity(inDash);
		finish();
	}

	/**
	 * Broadcast update view when have event
	 */
	final BroadcastReceiver broadcastUpdateForm = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			Log.e(TAG, "NHAN DC EXTRA");
			Bundle bundleMessageData = intent.getExtras();
			if (bundleMessageData != null) {
				try {

					int haveSms = bundleMessageData
							.getInt("receivetype");
					
					if (haveSms == 2) {
						String phone = bundleMessageData
								.getString("phonenumber");
						
						if(phone.contains("+") && phone.length()>4){
							phone = phone.substring(4);
						}
						Log.e(TAG , "phone = "+ phone);
						if (mPhoneNumber.contains(phone)) {
							String last_out_date = "";
							Calendar cal = Calendar.getInstance();
							SimpleDateFormat sdf = new SimpleDateFormat(
									"yyyy-MM-dd HH:mm:ss");
							last_out_date = sdf.format(cal.getTime());
							String content = bundleMessageData
									.getString("messenger");
							SmsBlockedItem item = new SmsBlockedItem(
									mPhoneNumber, last_out_date,
									SmsBlockedItem.RECEIVE, content .trim());
							listSms.add(item);
							adapterChatSms.notifyDataSetChanged();
							lvListChat.setSelection(adapterChatSms.getCount());
							
						}

					}

				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}
	};

	/**
	 * start service for page chat
	 * 
	 * @param context
	 */
	void startServicePageChat(Context context) {
		if (context == null) {
			return;
		}

		context.registerReceiver(broadcastUpdateForm, new IntentFilter(
				ApplicationConstants.TAG_BROADCAST));

	}

	/**
	 * update page chat when pull
	 * 
	 * @param offset
	 *            : start
	 * @param segment
	 *            : limit
	 */
	void updatePageChatWhenPull(int maxload) {
		if(mPhoneNumber.contains("+")){
			listSms = db.getSmsBlockItem(null, SmsBlockedItem.PHONE_NUMBER + " LIKE ?",
					new String[] { "%" + mPhoneNumber.substring(4) +"%" }, SmsBlockedItem.DATE_TIME
					+ " DESC", "" + maxload);
		}else{
			listSms = db.getSmsBlockItem(null, SmsBlockedItem.PHONE_NUMBER + " LIKE ?",
					new String[] { "%" + mPhoneNumber.substring(2) +"%" }, SmsBlockedItem.DATE_TIME
					+ " DESC", "" + maxload);
		}
		
		reverseArrayList();
	}

	/**
	 * reverse list sms to order by time ascen
	 */
	void reverseArrayList() {
		if (listSms != null && !listSms.equals(null) && listSms.size() > 0) {
			SmsBlockedItem temp = null;
			for (int i = 0; i < listSms.size() / 2; i++) {
				temp = listSms.get(i);
				listSms.set(i, listSms.get(listSms.size() - i - 1));
				listSms.set(listSms.size() - i - 1, temp);
			}
		}
	}

	//
	// menu item selected
	//
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();

			break;
		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	/**
	 * asynctask update view when pull
	 * 
	 * @author phuoctd
	 * 
	 */
	class UpdateListView extends AsyncTask<Void, Void, Void> {

		Context mContext;
		int oldPosition;
		Boolean stopped;

		public UpdateListView(Context context) {
			mContext = context;
			oldPosition = 0;
			stopped = false;
		}

		@Override
		protected void onPreExecute() {
			stopped = false;
			swipeContainer.setEnabled(false);
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(Void result) {

			super.onPostExecute(result);
			adapterChatSms = new AdapterChatSms(mContext,
					R.layout.item_search_notfound, listSms);
			lvListChat.setAdapter(adapterChatSms);
			lvListChat.setSelection(adapterChatSms.getCount() - oldPosition);

			if (listSms.size() < limitItemLoader) {
				lvListChat
						.setOnScrollListener(new AbsListView.OnScrollListener() {

							@Override
							public void onScrollStateChanged(AbsListView view,
									int scrollState) {

							}

							@Override
							public void onScroll(AbsListView view,
									int firstVisibleItem, int visibleItemCount,
									int totalItemCount) {

							}
						});

				swipeContainer.setEnabled(false);

			}
			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					
					swipeContainer.setRefreshing(false);
					stopped = true;
				}
			}, 1000);

		}

		@Override
		protected Void doInBackground(Void... params) {
			Log.e(TAG, "do back ground");
			oldPosition = limitItemLoader;
			limitItemLoader = lvListChat.getCount() + 30;
			updatePageChatWhenPull(limitItemLoader);

			return null;
		}

	}

	UpdateListView taskUpdateListView;
}
